package com.yl.plugin.method.dynamic;

import com.yl.plugin.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 动态查询的sql
 *
 * @author:liuxubo
 * @date:2023/7/13 15:05
 */
public class SelectSelectiveMethodGenerator {

    public Method buildSql(IntrospectedTable introspectedTable){
        String tableName = introspectedTable.getFullyQualifiedTableNameAtRuntime();
        String modelType = introspectedTable.getBaseRecordType();
        List<IntrospectedColumn> columnList = introspectedTable.getAllColumns();
        String columnStr = Util.strAndNewLine(columnList.stream().map(IntrospectedColumn::getActualColumnName)
                .map(s -> "\"" + s + "\"").collect(Collectors.toList()), ", ", 5, "\n                ");

        Method method = new Method("selectSelective");
        method.setVisibility(JavaVisibility.PUBLIC);

        FullyQualifiedJavaType parameterType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        Parameter parameter = new Parameter(parameterType, "row");
        method.addParameter(parameter);
        method.setReturnType(FullyQualifiedJavaType.getStringInstance());

        method.addBodyLine("SQL sql = new SQL();");
        method.addBodyLine("sql.SELECT(" + columnStr + ");");
        method.addBodyLine("sql.FROM(\"" + tableName + "\");");
        method.addBodyLine("");

        columnList.forEach(column -> {
            String actualColumnName = column.getActualColumnName();
            String javaProperty = column.getJavaProperty();
            String jdbcTypeName = column.getJdbcTypeName();

            String s = actualColumnName + " = #{" + javaProperty + ",jdbcType=" + jdbcTypeName + "}";
            method.addBodyLine("if (row.get" + StringUtils.capitalize(javaProperty) + "() != null) {");
            method.addBodyLine("sql.AND();");
            method.addBodyLine("sql.WHERE(\""+ s +"\");");
            method.addBodyLine("}");
            method.addBodyLine("");
        });

        method.addBodyLine("return sql.toString();");

        return method;
    }
}
